<template>
  <div id="coupleback">
    <group labelAlign="left" labelWidth="70px" labelMarginRight="5px">
      <x-input title="姓名" text-align="left" placeholder="输入姓名或昵称" required="required" v-model="Name" ref="input01"></x-input>
      <x-input title="手机号" placeholder="请输入手机号码" v-model="inputphone" is-type="china-mobile" ref="input02"></x-input>
      <!--  -->
      <x-textarea title="留言" :max="200" v-model="value" placeholder="请输入留言" :show-counter="false" :height="140" :rows="8" :cols="30"></x-textarea>
     </group>
     <!-- <span class="txt">请选择您希望回复时间</span> -->
      <!-- <div class="time">
        <div class="top">
          <span class="startTxt">开始时间</span><input type="text" class="star" v-model="starTime"  name="" placeholder="请选择开始时间">
          <popup-picker class="time1"  v-model="formatDemoValue1" :data="times"  @on-change="onChange1"></popup-picker>
        </div>
        <div class="bottom">
          <span class="endTxt">结束时间</span><input type="text" class="end" name="" placeholder="请选择结束时间" v-model="endTime">
          <popup-picker class="time2"  v-model="formatDemoValue2" :data="times"  @on-change="onChange2"></popup-picker>
        </div>
      </div> -->
      <div >
        <alert v-model="alert" >{{title}}</alert>
      </div>
    <box gap="20px 20px">
      <x-button type="primary" action-type="button" @click.native="Validform">提交</x-button>
    </box>
    <App-Mask1 :mask="mask"></App-Mask1>
    <loading :show="isLoading"></loading>
    <confirm v-model="isshowgetcard"
      title="提示"
      content="您现在还不是微信会员，请先领取微信会员卡"
      :close-on-confirm="false"
      @on-cancel="cancelGetCard"
      @on-confirm="showVipCard">
    </confirm>
  </div>
</template>
<script>
  import AppMask1 from '../../components/mask1/Mask1'
  import Box from 'vux/src/components/box'
  import XInput from 'vux/src/components/x-input'
  import XButton from 'vux/src/components/x-button'
  import Group from 'vux/src/components/group'
  import { Loading, XTextarea, PopupPicker, Alert, Confirm } from 'vux'

  let hours = []
  let mins = []
  for (var i = 0; i <= 23; i++) {
    if (i < 9) {
      i = '0' + i
    }
    hours.push({
      name: i + '',
      value: i + ''
    })
  }
  for (var j = 0; j <= 59; j++) {
    if (j < 9) {
      j = '0' + j
    }
    mins.push({
      name: j + '',
      value: j + ''
    })
  }
  export default {
    name: 'coupleback',
    components: {
      Loading,
      Box,
      XInput,
      XButton,
      Group,
      AppMask1,
      XTextarea,
      PopupPicker,
      Alert,
      Confirm
    },
    data () {
      return {
        title: '',
        isLoading: false,
        alert: false,
        value: '',
        starTime: '',
        endTime: '',
        formatDemoValue1: ['12', '30'],
        formatDemoValue2: ['12', '30'],
        times: [hours, mins],
        Name: '',
        inputphone: '',
        mask: {
          'isShow1': false,
          'isShow2': false
        },
        isshowgetcard: false
      }
    },
    created () {
      // 校验是否领卡
      this.$axios.post(this.apidomain + '/api/member/getIsActivateMemberCard/' + this.getCookie('appid'), {
        openId: this.getCookie('openid')
      })
      .then((response) => {
        if (response.data.data !== '1') {
          this.isshowgetcard = true
        }
      })
    },
    methods: {
      onChange1 (value, name) {
        this.starTime = `${value[0]}:${value[1]}`
      },
      onChange2 (value, name) {
        // console.log(this.format())
        this.endTime = `${value[0]}:${value[1]}`
        // console.log('new Value', value)
      },
      Validform () {
        this.valid1 = this.$refs.input01.valid
        this.valid2 = this.$refs.input02.valid
        if (this.valid1 === true && this.valid2 === true && this.$refs.input02.value !== '' && /^([0-9])*$/.test(this.value) === false && this.value !== '') {
          this.isLoading = true
          this.$axios.post(this.apidomain + '/api/feedback/saveFeedBack/' + this.getCookie('appid'), {
            openId: this.getCookie('openid'),
            name: this.Name,
            mobile: this.inputphone,
            // replyBeginTime: this.formatDemoValue1.slice().join(':'),
            // replyEndTime: this.formatDemoValue2.slice().join(':'),
            message: this.value
          })
          .then((response) => {
            if (response.data.errorCode === '0') {
              window.zhuge.track('Click', {
                '事件名称': '建议反馈-提交-点击',
                '姓名': this.Name,
                '感恩礼名称': response.data.data.name,
                'OpenID': this.getCookie('openid'),
                '点击时间': (new Date().toLocaleString())
              })
              this.isLoading = false
              if (response.data.data.type === 'coupon') {
                this.$set(this.mask, 'data', response.data.data)
                this.$set(this.mask, 'isShow1', true)
              }
              if (response.data.data.type === 'point') {
                this.$set(this.mask, 'data', response.data.data)
                this.$set(this.mask, 'isShow2', true)
              }
            } else if (response.data.errorCode === '1') {
              // this.$set(this.mask, 'data', response.data.data)
              this.alert = true
              this.title = '每天只能反馈一次哦,亲'
              this.isLoading = false
            }
          })
          .catch((error) => {
            this.isLoading = false
            console.log(error)
            // console.log(that.message)
          })
        } else if (this.valid1 === false && this.valid2 === true && this.value === '' && /^([0-9])*$/.test(this.value) === true) {
          this.alert = true
          this.title = '姓名不能为空'
        } else if (this.valid1 === true && (this.valid2 === false || this.$refs.input02.value === '') && this.value === '' && /^([0-9])*$/.test(this.value) === true) {
          this.alert = true
          this.title = '请输入正确的手机号码'
        } else if (this.valid1 === true && (this.valid2 === true || this.$refs.input02.value !== '') && this.value === '' && /^([0-9])*$/.test(this.value) === true) {
          this.alert = true
          this.title = '填写您的建议可领取感恩礼哦'
        } else if (this.valid1 === true && (this.valid2 === true || this.$refs.input02.value !== '') && this.value !== '' && /^([0-9])*$/.test(this.value) === true) {
          this.alert = true
          this.title = '留言内容格式有误，请重新录入'
        }
      },
      showVipCard () {
        // 未领取会员卡
        this.$axios.post(this.apidomain + '/api/card/getWxCardId/' + this.getCookie('appid'), {
          cardType: 'MEMBER_CARD'
        })
        .then((response) => {
          const timestamp = Date.parse(new Date()) / 1000
          const nonceStr = Math.random().toString(36).substr(2)
          this.getObjDetail(this.apidomain + '/api/wechat/mp/getCardApiTicket/' + this.getCookie('appid'))
          .then((data) => {
            const noncearr = [timestamp, response.data.data.cardId, data.data, nonceStr]
            noncearr.sort()
            const signature = this.$jssha(noncearr.join(''))
            this.$wechat.ready(() => {
              this.$wechat.addCard({
                cardList: [{
                  cardId: response.data.data.cardId,
                  cardExt: '{"timestamp": "' + timestamp + '", "nonce_str": "' + nonceStr + '", "signature": "' + signature + '"}'
                }],
                success: (res) => {
                  this.isLoading = false
                  this.isshowgetcard = false
                  window.location.reload()
                },
                cancel: (error) => {
                  this.isLoading = false
                  console.log(error)
                  window.alert('亲爱的用户，您还没有激活会员卡哦！')
                  window.WeixinJSBridge.invoke('closeWindow')
                }
              })
              if (navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1) {
                // 监听是否点击关闭原生卡
                document.addEventListener('visibilitychange', () => {
                  if (document.visibilityState !== 'hidden') {
                    window.WeixinJSBridge.invoke('closeWindow')
                  }
                })
              }
            })
          }, () => {})
          .catch((err) => {
            console.log(err)
            this.isLoading = false
          })
        })
        .catch((err) => {
          console.log(err)
          this.isLoading = false
        })
      },
      cancelGetCard () {
        window.WeixinJSBridge.invoke('closeWindow')
      }
    }
  }
</script>
<style lang="less">
  @import "../../assets/less/coupleback/coupleback.less";
</style>
